<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="所属试卷" prop="paperId" v-if="!paperId">
        <el-select v-model="queryParams.paperId" placeholder="请选择所属试卷" clearable>
          <el-option v-for="item in paperList" :key="item.baseId" :label="item.paperName" :value="item.baseId">
            <span style="float: left">{{ item.paperName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干" prop="subjectName">
        <el-input v-model="queryParams.subjectName" placeholder="请输入题干" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option v-for="dict in dict.type.tmlx" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:paperSubject:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:paperSubject:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:paperSubject:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:paperSubject:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperSubjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="baseId" v-if="false" />
      <el-table-column label="序号" align="center" width="50px">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1)*queryParams.pageSize+scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column label="所属试卷" width="200px" v-if="!paperId" align="center" prop="paperName" :show-overflow-tooltip="true" />
      <el-table-column label="题干" align="left" prop="subjectName" :show-overflow-tooltip="true" />
      <el-table-column label="类型" width="100px" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tmlx" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="分数" width="100px" align="center" prop="subjectScore" />
      <el-table-column label="操作" width="100px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:paperSubject:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:paperSubject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改题目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属试卷" prop="paperId" v-if="!paperId">
          <el-select v-model="form.paperId" placeholder="请选择所属试卷">
            <el-option v-for="item in paperList" :key="item.baseId" :label="item.paperName" :value="item.baseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题干" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入题干" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in dict.type.tmlx" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="选项设置">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addDomain">新增</el-button>
          <table style="margin-bottom: 5px;" v-if="form.paperSubjectOptions.length!=0" class="tableData" width="100%"
            cellpadding="0" cellspacing="0" border="0">
            <tr>
              <th width="5%">选项</th>
              <th width="70%">选项内容</th>
              <th width="15%">是否正确答案</th>
              <th width="10%">操作</th>
            </tr>
          </table>
          <el-checkbox-group :max="maxChoosed" v-model="checked">
            <table class="tableData" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr v-for="(domain, index) in form.paperSubjectOptions" :key="index">
                <td width="5%">
                  <el-tag>{{String.fromCharCode('A'.charCodeAt(0) + index)}}</el-tag>
                </td>
                <td width="70%">
                  <el-input v-model="domain.optionName" :placeholder="'选项'+(index+1)"></el-input>
                </td>
                <td width="15%">
                  <el-checkbox v-model="domain.trueOrFalse" :label="index"><br></el-checkbox>
                </td>
                <td width="10%">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="removeDomain(domain)">删除</el-button>
                </td>
              </tr>
            </table>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="分数" prop="subjectScore">
          <el-input v-model="form.subjectScore" @input="(v)=>(form.points=v.replace(/[^\d.]/g,''))" placeholder="请输入分数">
            <template slot="append">分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="答案解析" prop="analyzes">
          <el-input v-model="form.analyzes" type="textarea" placeholder="请输入答案解析" />
        </el-form-item>
        <el-form-item label="题目排序" prop="sort">
          <el-input-number v-model="form.sort"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPaperSubject,
    getPaperSubject,
    delPaperSubject,
    addPaperSubject,
    updatePaperSubject
  } from "@/api/business/paperSubject";
  import {
    paperList
  } from "@/api/business/paperInfo";

  export default {
    name: "PaperSubject",
    dicts: ['bmzt', 'tmlx'],
    props: {
      paperId: {
        type: String,
        default: ""
      },
    },
    watch: {
      paperId: {
        handler: function(val, oldVal) {
          this.queryParams.paperId = this.paperId;
          this.getList();
        },
        immediate: true
      }
    },
    computed: {
      //最多选中数量，多选100，单选1
      maxChoosed: function() {
        if (this.form.type == 0) {
          return 1
        } else {
          return 100
        }
      }
    },
    data() {
      return {
        checked: [],
        // 题目列表
        paperList: [],

        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 题目管理表格数据
        paperSubjectList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          subjectName: undefined,
          type: undefined,
          paperId: this.paperId,
        },
        // 表单参数
        form: {
          paperSubjectOptions: [],
        },
        // 表单校验
        rules: {
          paperId: [{
            required: true,
            message: "所属试题不能为空",
            trigger: "blur"
          }],
          subjectName: [{
            required: true,
            message: "题干不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "类型不能为空",
            trigger: "change"
          }],
          subjectScore: [{
            required: true,
            message: "分数不能为空",
            trigger: "blur"
          }],
          rightAnswer: [{
            required: true,
            message: "正确答案不能为空",
            trigger: "blur"
          }],
          sort: [{
            required: true,
            message: "题目排序不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询题目管理列表 */
      getList() {
        this.loading = true;
        listPaperSubject(this.queryParams).then(response => {
          this.paperSubjectList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //添加一个选项
      addDomain() {
        if (this.form.type == undefined) {
          this.$modal.msgError("请先选择题目类型！");
        } else {
          this.form.paperSubjectOptions.push({
            optionName: null,
            sort: this.form.paperSubjectOptions.length,
            trueOrFalse: null,
          });
        }
      },
      //删除选项
      removeDomain(item) {
        var index = this.form.paperSubjectOptions.indexOf(item)
        if (index !== -1) {
          this.form.paperSubjectOptions.splice(index, 1)
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.checked = []
        this.form = {
          baseId: undefined,
          paperId: this.paperId,
          subjectName: undefined,
          type: undefined,
          subjectScore: undefined,
          analyzes: undefined,
          rightAnswer: undefined,
          sort: undefined,
          paperSubjectOptions: [],
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加题目";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const baseId = row.baseId || this.ids
        getPaperSubject(baseId).then(response => {
          this.loading = false;
          this.form = response.data;
          //处理选项单选多选
          this.form.paperSubjectOptions.forEach((item, index) => {
            if (item.trueOrFalse) {
              this.checked.push(index)
            }
          })
          this.open = true;
          this.title = "修改题目管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.paperSubjectOptions.length == 0) {
              this.$modal.msgError("请添加题目选项！");
            } else {
              //处理选项单选多选
              this.form.paperSubjectOptions.map((item, index) => {
                if (this.checked.includes(index)) {
                  item.trueOrFalse = true
                } else {
                  item.trueOrFalse = false
                }
              })
              this.buttonLoading = true;
              if (this.form.baseId != null) {
                updatePaperSubject(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              } else {
                addPaperSubject(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              }
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const baseIds = row.baseId || this.ids;
        this.$modal.confirm('是否确认删除题目管理编号为"' + baseIds + '"的数据项？').then(() => {
          this.loading = true;
          return delPaperSubject(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/paperSubject/export', {
          ...this.queryParams
        }, `paperSubject_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>
  .tableData {
    border: 0;
    font-size: 26rpx;
    border-collapse: collapse;
    border-spacing: 0;
    width: 100%;
    border-radius: 8rpx;
  }

  .tableData td {
    height: 40px;
    font-size: 24rpx;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: 500;
    color: #666666;
    border: 1rpx solid #EDEDED;
    border-collapse: collapse !important;
    text-align: center;
  }

  .tableData th {
    height: 40px;
    font-size: 24rpx;
    font-family: PingFang SC-Bold, PingFang SC;
    font-weight: bold;
    color: #333333;
    background: rgba(15, 98, 254, 0.1);
    border: 1rpx solid #EDEDED;
  }
</style>
